package com.dai.provider_hystrix3004.controller;

import com.dai.com_api.entity.Dept;
import com.dai.provider_hystrix3004.impl.DeptService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class DeptController {

    @Autowired
    private DeptService deptService;
    //提供服务发现的 - 一定要引入 org.springframework.cloud 包下的 DiscoveryClient
    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping("/dept/add")
    public boolean add(@RequestBody Dept dept) {
        return deptService.add(dept);
    }

    @RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
    //定义本路由的熔断器方法 - 只有在路由上加了这种熔断方法的才能进行HystrixDashboard进行监控
    @HystrixCommand(fallbackMethod = "getHystrix")
    public Dept get(@PathVariable("id") int id) {
        Dept dept = deptService.findById(id);
        if (null == dept) {
            throw new RuntimeException("手动调用熔断器");
        }
        return dept;
    }

    //上一个/dept/get/{id}这个路由的熔断方法
    public Dept getHystrix(@PathVariable("id") int id) {
        return new Dept().setDeptno(0).setDname("没有" + id + "数据");
    }

    @RequestMapping("/dept/list")
    public List<Dept> list() {
        return deptService.findAll();
    }

    @RequestMapping("/get/service")
    public Object getService() {
        //得到所有微服务 - 称为 “服务发现”  配合在本启动类的@EnableDiscoveryClient 使用
        List<String> list = discoveryClient.getServices();
        System.out.println(list);

        //根据微服务名称(spring.application.name配置的)来得到具体的某个微服务
        List<ServiceInstance> srvList = discoveryClient.getInstances("DAI-PROVIDER-3001");
        for (ServiceInstance element : srvList) {
            System.out.println("ServiceId:" + element.getServiceId() + "  host:" + element.getHost() + "  port:" + element.getPort() + "  url:" + element.getUri());
        }

        return this.discoveryClient;
    }
}
